package com.epam.qanda.web.servlet.admin;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.qanda.comparator.EmailComparator;
import com.epam.qanda.comparator.FNameComparator;
import com.epam.qanda.comparator.LNameComparator;
import com.epam.qanda.comparator.LoginComparator;
import com.epam.qanda.comparator.RoleComparator;
import com.epam.qanda.db.model.Role;
import com.epam.qanda.db.model.User;
import com.epam.qanda.db.service.RoleService;
import com.epam.qanda.db.service.UserService;

public class AdminPageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = Logger.getLogger("stdout");

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String url = request.getServletPath();
		List<User> users = new UserService().getAllUsers();
		List<Role> roles = new RoleService().getAllRoles();
		LOG.info("List of users: " + users.size() + "; List of roles: " + roles.size());

		if (url.equals("/sortRole")) {
			RoleComparator role = new RoleComparator();
			Collections.sort(users, role);
		}
		if (url.equals("/sfName")) {
			FNameComparator fName = new FNameComparator();
			Collections.sort(users, fName);
		}
		if (url.equals("/slName")) {
			LNameComparator lNAme = new LNameComparator();
			Collections.sort(users, lNAme);
		}
		if (url.equals("/sLogin")) {
			LoginComparator login = new LoginComparator();
			Collections.sort(users, login);
		}
		if (url.equals("/sEmail")) {
			EmailComparator email = new EmailComparator();
			Collections.sort(users, email);
		}

		request.setAttribute("users", users);
		request.setAttribute("roles", roles);

		request.getRequestDispatcher("WEB-INF/pages/adminPage.jsp").forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
